<template>
  <custom-modal-page :visible.sync="visible">
    <div class="beam-layout-container" id="beam-layout-container">
      <!-- 顶部查询条件 -->
      <div class="screen-conditions-container">
        <ScreenConditions :isDataType="false">
          <template slot="conditions">
            <a-input
              placeholder="请输入文件名"
              v-model="conditions.name"
              allowClear
            />
            <bjRangeCalendar
              :format="conditions.dateFormat"
              v-model="conditions.dateRange"
              :show-time="{ format: conditions.dateFormat }"
              :activeDate="conditions.hasDataDateList"
              @ok="calendarOk"
            ></bjRangeCalendar>
          </template>
          <template slot="operate">
            <a-button type="primary" @click="getData()"> 查询 </a-button>
            <a-button type="default" @click="goBack()" class="back-button">
              返回
            </a-button>
          </template>
        </ScreenConditions>
      </div>
      <div class="beam-table-container" v-loading="loading">
        <div class="table-header" header="检测报告">
          <div>
            <a-button type="primary" @click="addModalVisible = true">
              上传文件
            </a-button>
          </div>
        </div>
        <div class="main">
          <vxe-table
            ref="xTable"
            height="99%"
            class="scrollbarStyle"
            align="center"
            show-overflow
            show-header-overflow
            :data="tableData"
            :column-config="{ resizable: true }"
          >
            <vxe-column type="seq" width="80" title="序号"></vxe-column>
            <vxe-column
              show-overflow
              :key="index"
              :title="item.title"
              :field="item.key"
              :width="item.width"
              v-for="(item, index) in columns"
            >
              <template #default="{ row }">
                <div>{{ row[item.key] }}</div>
              </template>
            </vxe-column>
            <vxe-column
              field="operate"
              width="220"
              title="操作"
              fixed="right"
              align="left"
            >
              <template #default="{ row }">
                <div class="text-button-group">
                  <a-button type="link" @click="preview(row)"> 预览 </a-button>
                  <a-button type="link" @click="download(row)"> 下载 </a-button>
                  <a-button
                    type="link"
                    class="danger"
                    @click="handleDelClick(row)"
                  >
                    删除
                  </a-button>
                </div>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <div class="pager-container">
          <vxe-pager
            background
            :current-page.sync="pager.page"
            :page-size.sync="pager.pageSize"
            :total="pager.total"
            :layouts="[
              'PrevPage',
              'JumpNumber',
              'NextPage',
              'Sizes',
              'FullJump',
            ]"
            @page-change="paginationChange"
          >
            <template #left>
              <div class="vxe-pager-left-tip-container">
                第<span>1</span>到<span
                  >{{ Math.ceil(pager.total / pager.pageSize) || 1 }}页 </span
                >共<span>{{ pager.total }}</span
                >条记录
              </div>
            </template>
          </vxe-pager>
        </div>
      </div>
      <!-- 上传文件【弹窗】-->
      <a-modal
        title="上传文件"
        centered
        v-model="addModalVisible"
        width="650px"
        wrapClassName="choose-report-modal"
        @ok="handleOk()"
        @cancel="handleClose()"
      >
        <div class="choose-report-modal-body">
          <a-form-model ref="modalForm" :model="modalForm" :rules="modalRules">
            <a-form-model-item
              label="上传文件:"
              prop="address"
              :rules="{
                required: true,
                validator: validateFile,
              }"
            >
              <bj-upload-file
                v-model="modalForm.fileList"
                :viewMode="false"
                :count="20"
                :replaceFields="{
                  fileName: 'realFileName',
                  fileSize: 'fileSize',
                  fileType: 'fileType',
                  fileUrl: 'fileUrl',
                }"
              ></bj-upload-file>
            </a-form-model-item>
          </a-form-model>
        </div>
      </a-modal>
    </div>
  </custom-modal-page>
</template>
<script>
import bjRangeCalendar from "@/components/bj-range-calendar";
import {
  getReportList,
  deleteReport,
  uploadReport,
} from "@/api/wisdom-beam/material-app";
import { commonViewFile, commonDownloadFile, notificationTip } from "@/utils";
import bjUploadFile from "@/components/bj-upload-file";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: "",
    },
    type: {
      type: [String, Number],
      default: "",
    },
  },
  components: {
    bjRangeCalendar,
    bjUploadFile,
  },
  data() {
    return {
      modalForm: {
        fileList: [],
      },
      modalRules: {},
      addModalVisible: false,
      loading: false,
      conditions: {
        //文件名
        name: "",
        //日期
        dateFormat: "YYYY-MM-DD HH:mm:ss",
        dateRange: [],
        hasDataDateList: [],
      },
      columns: [
        {
          title: "文件名",
          key: "realFileName",
        },
        {
          title: "上传人",
          key: "createrName",
        },
        {
          title: "上传时间",
          key: "createTime",
        },
      ],
      tableData: [],
      pager: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },

  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    //确定
    handleOk() {
      this.$refs.modalForm.validate(async (valid) => {
        if (valid) {
          let uploadFiles = this.modalForm.fileList.map((v) => v.file);
          let formdata = new FormData();
          for (let i = 0; i < uploadFiles.length; i++) {
            formdata.append("uploadFiles", uploadFiles[i]);
          }
          uploadReport({
            formdata,
            inbaseId: this.id,
          })
            .then((res) => {
              notificationTip("success", "操作成功！");
              this.handleClose();
              this.getData();
            })
            .catch((_) => {})
            .finally((_) => {});
        } else {
          return false;
        }
      });
    },

    //关闭弹窗
    handleClose() {
      this.$refs.modalForm.resetFields();
      this.modalForm.fileList = [];
      this.addModalVisible = false;
    },

    //验证文件
    validateFile(rule, value, callback) {
      let { fileList } = this.modalForm;
      if (fileList.length == 0) {
        callback(new Error(`请选择文件`));
      } else {
        callback();
      }
    },

    //查询列表数据
    getData() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        let { page, pageSize } = this.pager;
        let { id, conditions } = this;
        getReportList({
          page,
          pageSize,
          id,
          name: conditions.name ?? "",
          startTime: conditions?.dateRange?.[0] ?? "",
          endTime: conditions?.dateRange?.[1] ?? "",
        })
          .then((res) => {
            let { data } = res;
            this.tableData = data?.result?.records || [];
            this.pager.total = data?.result?.total ?? 0;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听日期选择
    calendarOk() {
      this.getData();
    },

    //删除
    handleDelClick(row) {
      let that = this;
      let dataLength = that.tableData.length;
      let { id } = row;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定删除所选内容?",
        content: "删除内容后,将无法恢复。",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FB5A5A",
          }),
        onOk() {
          deleteReport({ id })
            .then((res) => {
              if (dataLength == 1 && that.pager.page > 1) {
                that.pager.page -= 1;
              }
              notificationTip("success", "删除成功！");
              that.getData();
            })
            .catch();
        },
        onCancel() {},
      });
    },

    //预览
    preview(row = {}) {
      commonViewFile("beam", row.id);
    },

    //下载
    download(row = {}) {
      let { realFileName, id, fileType } = row;
      commonDownloadFile("beam", id, realFileName, fileType);
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getData();
    },

    goBack() {
      this.$emit("update:visible", false);
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.choose-report-modal {
  .choose-report-modal-body {
    height: 200px;
    .ant-form-item {
      .flex();
      .ant-form-item-label {
        label {
          color: #999;
        }
      }
    }
  }
}
.beam-layout-container {
  box-sizing: border-box;
  height: 100%;
  .flex();
  flex-direction: column;
  .back-button {
    position: absolute;
    top: 11px;
    right: 20px;
  }
}
</style>
